package com.bristua.mall;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HeaderElement;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.IOUtils;

public class ImagePreProcess {

    public static int isBlack(int colorInt) {
        Color color = new Color(colorInt);
        if (color.getRed() + color.getGreen() + color.getBlue() <= 100) {
            return 1;
        }
        return 0;
    }

    public static int isWhite(int colorInt) {
        Color color = new Color(colorInt);
        if (color.getRed() + color.getGreen() + color.getBlue() > 100) {
            return 1;
        }
        return 0;
    }

    public static BufferedImage removeBackgroud(String picFile)
            throws Exception {
        BufferedImage img = ImageIO.read(new File(picFile));
        int width = img.getWidth();
        int height = img.getHeight();
        for (int x = 0; x < width; ++x) {
            for (int y = 0; y < height; ++y) {
                if (isWhite(img.getRGB(x, y)) == 1) {
                    img.setRGB(x, y, Color.WHITE.getRGB());
                } else {
                    img.setRGB(x, y, Color.BLACK.getRGB());
                }
            }
        }
        return img;
    }

    public static List<BufferedImage> splitImage(BufferedImage img)
            throws Exception {
        List<BufferedImage> subImgs = new ArrayList<BufferedImage>();
        subImgs.add(img.getSubimage(10, 6, 8, 10));
        subImgs.add(img.getSubimage(19, 6, 8, 10));
        subImgs.add(img.getSubimage(28, 6, 8, 10));
        subImgs.add(img.getSubimage(37, 6, 8, 10));
        return subImgs;
    }

    public static Map<BufferedImage, String> loadTrainData() throws Exception {
        Map<BufferedImage, String> map = new HashMap<BufferedImage, String>();
        File dir = new File("train");
        File[] files = dir.listFiles();
        for (File file : files) {
            if(file.isDirectory()){
                File[] files1 = file.listFiles();
                for(File file1 : files1){
                    map.put(ImageIO.read(file), file.getName().charAt(0) + "");
                }
            }

        }
        return map;
    }

    public static String getSingleCharOcr(BufferedImage img,
                                          Map<BufferedImage, String> map) {
        String result = "";
        int width = img.getWidth();
        int height = img.getHeight();
        int min = width * height;
        for (BufferedImage bi : map.keySet()) {
            int count = 0;
            Label1:
            for (int x = 0; x < width; ++x) {
                for (int y = 0; y < height; ++y) {
                    if (isWhite(img.getRGB(x, y)) != isWhite(bi.getRGB(x, y))) {
                        count++;
                        if (count >= min)
                            break Label1;
                    }
                }
            }
            if (count < min) {
                min = count;
                result = map.get(bi);
            }
        }
        return result;
    }

    public static String getAllOcr(String file) throws Exception {
        BufferedImage img = removeBackgroud(file);
        List<BufferedImage> listImg = splitImage(img);
        Map<BufferedImage, String> map = loadTrainData();
        String result = "";
        for (BufferedImage bi : listImg) {
            result += getSingleCharOcr(bi, map);
        }
        ImageIO.write(img, "JPEG", new File("result\\" + result + ".jpg"));
        return result;
    }

    public static Map<String,Object> downloadImage() {
        StringBuilder cookies = new StringBuilder();
        long time = System.currentTimeMillis();
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(
                "https://s.lakala.com/api/v1/captcha.jpg?" + System.currentTimeMillis());
        try {
            // 执行getMethod
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: "
                        + getMethod.getStatusLine());
            }
            // 读取内容
            String picName = "d:\\img\\" + time + ".JPEG";
            InputStream inputStream = getMethod.getResponseBodyAsStream();
            Header[] responseHeaders = getMethod.getResponseHeaders();
            if(responseHeaders!=null && responseHeaders.length>0){
                for(Header header : responseHeaders){
                    HeaderElement[] elements = header.getElements();
                    if(elements!=null && elements.length>0){
                        for(HeaderElement headerElement : elements){
                            if("bmmp4SessionId".equals(headerElement.getName()) || "route".equals(headerElement.getName()) || "aliyungf_tc".equals(headerElement.getName())){
                                cookies.append(headerElement.getName()+"="+headerElement.getValue()+";");
                            }
                            System.out.println(headerElement.getName()+":"+headerElement.getValue());
                        }
                    }
                    System.out.println(header.getName()+":"+header.getValue());
                }
            }
            cookies.append("NTKF_T2D_CLIENTID=guest1CD1BE65-15AF-0754-69A5-F41ACB7F8A2D;")
                    .append("UM_distinctid=16af41b50e0156-03a9eac6acf7ce-651a107e-1fa400-16af41b50e16ba; Hm_lvt_c968abbd69153a3bb1e5d27388c957df=1558873558,1558873622;");

            OutputStream outStream = new FileOutputStream(picName);
            IOUtils.copy(inputStream, outStream);
            outStream.close();
            Map<String,Object> map = new HashMap<>();
            map.put("fileName",picName);
            map.put("cookie",cookies.toString());
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            getMethod.releaseConnection();
        }
        return null;
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
//        downloadImage();
        String allOcr = getAllOcr("D:\\img\\1559055598363.JPEG");
        System.out.println(allOcr);
//        for (int i = 0; i < 30; ++i) {
//            String text = getAllOcr("img\\" + i + ".JPEG");
//            System.out.println(i + ".JPEG = " + text);
//        }
    }
}
